package com.example.homewidgets

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.Message
import android.os.Messenger
import android.view.View
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.homewidgets.ui.theme.HomewidgetsTheme

class MainActivity : ComponentActivity(), ServiceConnection {

    private var mServiceMessenger: Messenger? = null
    private val mActivityMessenger = Messenger(Handler(Looper.getMainLooper()) { message ->
        // 处理从Service接收到的消息
        val bundle = message.data
        val string = bundle.getString("key")
        println("收到消息：$string")
        true
    })

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.layout_main)

        // 获取传递的数据
        handleEvent(intent)

        val intent = Intent(this, MyWidgetService::class.java)
        bindService(intent, this, Context.BIND_AUTO_CREATE)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        // 如果MainActivity已经在前台运行，这里也可以获取传递的数据
        handleEvent(intent)
    }

    // 处理意图
    fun handleEvent(intent: Intent?) {
        val widgetId = intent?.getIntExtra("widgetId", -1)
        val stringExtra = intent?.getStringExtra("extraString")
        if (widgetId != -1) {
            println("传递给主app的：$widgetId,$stringExtra")
        }
    }

    fun onClick(view: View) {
        val refreshIntent = Intent(this, NewAppWidget::class.java).apply {
            action = MyActions.CLICK_APP2Widget
            putExtra("widgetId", 12)
            putExtra("key", "app通知到了widget刷新")
        }
        sendBroadcast(refreshIntent)

    }

    override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
        mServiceMessenger = Messenger(service)
        val msg = Message.obtain(null, 1)
        msg.replyTo = mActivityMessenger
        mServiceMessenger?.send(msg)
    }

    override fun onServiceDisconnected(name: ComponentName?) {

    }


}

@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
    Text(
        text = "Hello $name!",
        modifier = modifier
    )
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    HomewidgetsTheme {
        Greeting("Android")
    }
}